package com.xiaoxin.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * @author: ZhangXX
 * @createTime: 2024-08-31 10:21
 **/
@Slf4j
@Configuration
public class HttpConfiguration {

    /**
     * 没有实例化RestTemplate时，初始化RestTemplate
     *
     * @return
     */
    @ConditionalOnMissingBean(RestTemplate.class)
    @Bean
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        // 设置读取超时
        factory.setReadTimeout(500000);
        // 设置连接超时，单位毫秒
        factory.setConnectTimeout(500000);
        RestTemplate restTemplate = new RestTemplate(factory);
        // 支持中文编码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        //添加一个拦截器，在请求头部添加Authorization鉴权码
/*        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add("Authorization", "xxxxxXXXXX");
            return execution.execute(request, body);
        });*/
        log.info("RestTemplate初始化完成");
        return restTemplate;
    }
}
